package com.app.onebuy.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.app.onebuy.R;
import com.app.onebuy.basis.BasisActivity;
import com.app.onebuy.basis.Constants;
import com.app.onebuy.bean.BaseListData;
import com.app.onebuy.bean.BaseListDataListBean;
import com.app.onebuy.bean.BasicBeanStr;
import com.app.onebuy.bean.BasisBean;
import com.app.onebuy.bean.OrderPaypalInfoBean;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.DialogUtils;
import my.IntentUtils;
import my.MySharedPreferences;
import my.PayPalUtil;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 充值 账户充值
 */
public class ChargeActivity extends BasisActivity {


    @BindView(R.id.recyclerview_pay)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_pay_num)
    TextView mTvPayNum;
    @BindView(R.id.edit_num)
    EditText numEdit;


    private MyAdapterList mAdapter;
    private BaseListDataListBean mListBean;

    //    private int currentPosition = 0;
//    private String payName = "";
    BaseListData currentPayWay;

    public static final int PAY_TYPE_PAYPAL = 1, PAY_TYPE_GLOBELABS = 2, PAY_TYPE_MAYA = 3, PAY_TYPE_NAMICS = 4, PAY_TYPE_FORTUMO = 5, PAY_TYPE_WECHAT = 6;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.user_charge_activity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        setTitle(R.string.recharge);
        setTitleLeftButton(null);
        numEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
                Log.e("输入过程中执行该方法", "文字变化");
                if (TextUtils.isEmpty(s)) {
                    mTvPayNum.setText("0");
                } else {
                    mTvPayNum.setText("" + s);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // 输入前的监听
                Log.e("输入前确认执行该方法", "开始输入");

            }
        });

        PayPalUtil.getInstance().startPayPalService(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBean = new BaseListDataListBean();
        setListView();
//        mRecyclerView.refresh();
//        getFromCache();

        addfack();
        EventBus.getDefault().register(this);
    }

    void addfack() {
        BaseListData data;

//        data = new BaseListData("","支付宝支付");
//        mListBean.getList().add(data);
//        data = new BaseListData("","微信支付");
//        mListBean.getList().add(data);

        data = new BaseListData("", "Paynamics(7-eleven,G cash)");
        data.setType(PAY_TYPE_NAMICS);
        mListBean.getList().add(data);

        data = new BaseListData("", "PayPal");
        data.setType(PAY_TYPE_PAYPAL);
        mListBean.getList().add(data);

//        data = new BaseListData("","Fortumo");
//        data.setType(PAY_TYPE_FORTUMO);
//        mListBean.getList().add(data);

        data = new BaseListData("", mContext.getString(R.string.order_pay_bywechat));
        data.setType(PAY_TYPE_WECHAT);
        mListBean.getList().add(data);

//        data = new BaseListData("","Globelabs");
//        data.setType(PAY_TYPE_GLOBELABS);
//        mListBean.getList().add(data);

//        data = new BaseListData("","Paymaya");
//        data.setType(PAY_TYPE_MAYA);
//        mListBean.getList().add(data);


        currentPayWay = mListBean.getList().get(0);
        setListView();
    }

//    private void getFromCache() {
//
//        DothingsListBean beanCaceh = (DothingsListBean) DothingsListBean.getObjFromCache(id);
//        if (beanCaceh != null) {
//            mListBean = beanCaceh;
//            setListView();
//        } else {
//            mListBean = new ServiceNewListBean();
//            setListView();
//            getList();
//        }
//    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }


    private void getList() {
        MyParams params = new MyParams();
//        showProgress();
//        params.put("parentId", channelListData.getPARENTID());
//        params.put("sortId", sortDataBean.getSortId());
//        MyHttpUtils.post(Constants.URL_APP_SERVER_LIST, params, myHttpListener,
//                HTTP_LIST, AppListBean.class);

    }

    private final static int HTTP_LIST = 11;
    MyHttpListener myHttpListener = new MyHttpListener() {
        @Override
        public void onSuccess(int httpWhat, Object result) {
//            mListBean = (AppListBean) result;
//            setListView();
        }

        @Override
        public void onFailure(int httpWhat, Object result) {
            super.onFailure(httpWhat, result);
//            mListBean = new ServiceNewListBean();
            setListView();
        }

        @Override
        public void onFinish(int httpWhat) {
//            hideLoading();
        }
    };


    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_charge_payway_list_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
            final BaseListData data = mListBean.getList().get(position);
//            payName = mListBean.getList().get(currentPosition).getName();
            viewHolder.text_name.setText(data.getName());
            viewHolder.img_check.setImageResource(data.getType() == currentPayWay.getType() ? R.drawable.icon_checkbox_red_cheked : R.drawable.icon_checkbox_unchecked);
            viewHolder.list_item.setTag(data);
//            viewHolder.list_item.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    currentPosition = position;
//                    payName = data.getName();
//                    notifyDataSetChanged();
//                }
//            });
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.img_icon)
            public ImageView img_check;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {
                BaseListData data = (BaseListData) v.getTag();
                currentPayWay = data;
                notifyDataSetChanged();
//                    data.toDetail(mContext);
            }
        }
    }

    @OnClick(R.id.btn_ok)
    public void toPay() {
        String moneyNum = numEdit.getText().toString().trim();
        if (TextUtils.isEmpty(moneyNum)) {
            showToast("" + getString(R.string.charge_num_can_not_null));
            return;
        }
        if (Long.valueOf(moneyNum) <= 0) {

            showToast("" + getString(R.string.charge_num_can_not_null));
            return;
        }


        switch (currentPayWay.getType()) {
            case PAY_TYPE_PAYPAL:
//                PayPalUtil.getInstance().doPayPalPay(this,moneyNum,"paypal支付");
                if (Long.valueOf(moneyNum) < 300) {

                    showToast("" + getString(R.string.charge_num_can_not_lower_than));
                    return;
                }
                getPayPalInfo(moneyNum);
                break;
            case PAY_TYPE_GLOBELABS:
                if (Long.valueOf(moneyNum) < 10) {

                    showToast("" + getString(R.string.charge_num_can_not_lower_than_ten));
                    return;
                }

                getGlobelabsInfo(moneyNum);
                break;
            case PAY_TYPE_MAYA:
                if (Long.valueOf(moneyNum) < 10) {

                    showToast("" + getString(R.string.charge_num_can_not_lower_than_ten));
                    return;
                }

                getPayMayaInfo(moneyNum);

                break;
            case PAY_TYPE_NAMICS:
                if (Long.valueOf(moneyNum) < 10) {

                    showToast("" + getString(R.string.charge_num_can_not_lower_than_ten));
                    return;
                }

                getPayNamicsInfo(moneyNum);
                break;
            case PAY_TYPE_FORTUMO:
                if (Long.valueOf(moneyNum) < 10) {

                    showToast("" + getString(R.string.charge_num_can_not_lower_than_ten));
                    return;
                }

                getFortumoInfo(moneyNum);
                break;
            case PAY_TYPE_WECHAT:
                if (Long.valueOf(moneyNum) < 10) {
                    showToast("" + getString(R.string.charge_num_can_not_lower_than_ten));
                    return;
                }

                getWechatInfo(moneyNum);
                break;
            default:
                showToast("");
                break;
        }
    }

    OrderPaypalInfoBean paypalInfoBean;

    public void getPayPalInfo(String moneyNum) {
        MyParams params = new MyParams();
        showProgress();
        params.put("recharge_amount", moneyNum);
        MyHttpUtils.post(Constants.URL_PAYPAL_CHARGE_RECHARGE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        paypalInfoBean = (OrderPaypalInfoBean) result;
                        IntentUtils.ViewUrl(mContext, paypalInfoBean.getApproval_url(), REQUEST_BUY);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, OrderPaypalInfoBean.class);
    }

    public void getGlobelabsInfo(String moneyNum) {
        MyParams params = new MyParams();
        showProgress();
        params.put("recharge_amount", moneyNum);
        MyHttpUtils.post(Constants.URL_GLOBELABS_CHARGE_RECHARGE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        paypalInfoBean = (OrderPaypalInfoBean) result;
                        IntentUtils.ViewUrl(mContext, paypalInfoBean.getPay_url(), REQUEST_BUY);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, OrderPaypalInfoBean.class);
    }

    public void getPayMayaInfo(String moneyNum) {
        MyParams params = new MyParams();
        showProgress();
        params.put("recharge_amount", moneyNum);
        MyHttpUtils.post(Constants.URL_API + "account/paymaya_recharge", params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        paypalInfoBean = (OrderPaypalInfoBean) result;
                        IntentUtils.ViewUrl(mContext, paypalInfoBean.getPay_url(), REQUEST_BUY);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, OrderPaypalInfoBean.class);
    }

    public void getPayNamicsInfo(String moneyNum) {
        MyParams params = new MyParams();
        showProgress();
        params.put("recharge_amount", moneyNum);
        MyHttpUtils.post(Constants.URL_API + "account/paynamics_recharge", params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        paypalInfoBean = (OrderPaypalInfoBean) result;
                        IntentUtils.ViewUrl(mContext, paypalInfoBean.getPay_url(), REQUEST_BUY);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, OrderPaypalInfoBean.class);
    }

    public void getFortumoInfo(String moneyNum) {
        MyParams params = new MyParams();
        showProgress();
        params.put("recharge_amount", moneyNum);
        MyHttpUtils.post(Constants.URL_FORTUMO_CHARGE_RECHARGE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        paypalInfoBean = (OrderPaypalInfoBean) result;
                        IntentUtils.ViewUrl(mContext, paypalInfoBean.getPay_url(), REQUEST_BUY);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, OrderPaypalInfoBean.class);
    }

    public void getWechatInfo(String moneyNum) {
        MyParams params = new MyParams();
        showProgress();
        params.put("recharge_amount", moneyNum);
        params.put("service", "pay.weixin.raw.app");
        MyHttpUtils.post(Constants.URL_WECHAT_CHARGE_RECHARGE, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {

                com.alibaba.fastjson.JSONObject response = com.alibaba.fastjson.JSONObject.parseObject(((BasisBean) result).getResultData());
                try {
                    int codeStatus = response.getInteger("status");
                    if (codeStatus == 200) {
                        String payjson = response.getString("info");
                        onWechatPayinfoget(payjson);
                    } else {
                        hideLoading();
                        if (!TextUtils.isEmpty(response.getString("info"))) {
                            DialogUtils.DialogOkMsg(mContext, response.getString("info"), null);
                        } else {
                            DialogUtils.DialogOkMsg(mContext, "Failed", null);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    dismissProgress();
                    DialogUtils.DialogOkMsg(mContext, "Failed", null);
                }
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
                super.onFailure(httpWhat, result);
                DialogUtils.DialogOkMsg(mContext, "failed", null);

            }

            @Override
            public void onFinish(int httpWhat) {

            }
        }, 0, BasicBeanStr.class);

//                MyHttpUtils.post(Constants.URL_WECHAT_CHARGE_RECHARGE, params, new Callback() {
//                    @Override
//                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                        dismissProgress();
////                if(!TextUtils.isEmpty(responseString)){
////                    com.alibaba.fastjson.JSONObject objInfo = JSON.parseObject(responseString);
////                    DialogUtils.DialogOkMsg(mContext,objInfo.getString("info"),null);
////                }else {
////                    DialogUtils.DialogOkMsg(mContext,"failed",null);
////                }
//                        DialogUtils.DialogOkMsg(mContext, "failed", null);
//                    }
//
//                    @Override
//                    public void onResponse(@NotNull Call call, @NotNull Response responseR) throws IOException {
//
//                        com.alibaba.fastjson.JSONObject response = com.alibaba.fastjson.JSONObject.parseObject(responseR.body().string());
//                        try {
//                            int codeStatus = response.getInteger("status");
//                            if (codeStatus == 200) {
//                                String payjson = response.getString("info");
//                                onWechatPayinfoget(payjson);
//                            } else {
//                                hideLoading();
//                                if (!TextUtils.isEmpty(response.getString("info"))) {
//                                    DialogUtils.DialogOkMsg(mContext, response.getString("info"), null);
//                                } else {
//                                    DialogUtils.DialogOkMsg(mContext, "Failed", null);
//                                }
//                            }
//
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            dismissProgress();
//                            DialogUtils.DialogOkMsg(mContext, "Failed", null);
//                        }
//
//                    }
//                });
    }

    private IWXAPI api;

    void onWechatPayinfoget(String payjson) {

        com.alibaba.fastjson.JSONObject objInfo = JSON.parseObject(payjson);
        String strPayinfo = objInfo.getString("pay_info");
//        LogUtil.i("onWechatPayinfoget--strPayinfo-->"+strPayinfo);
//        com.alibaba.fastjson.JSONObject json = objInfo.getJSONObject("pay_info");
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(strPayinfo);

        String appid = json.getString("appid");
        new MySharedPreferences(mContext).putString("wechat_appid", appid);
        api = WXAPIFactory.createWXAPI(this, appid);

//        IWXAPI
        PayReq req = new PayReq();
        req.appId = json.getString("appid");
        req.partnerId = json.getString("partnerid");
        req.prepayId = json.getString("prepayid");
        req.nonceStr = json.getString("noncestr");
        req.timeStamp = json.getString("timestamp");
        req.packageValue = json.getString("package");
        req.sign = json.getString("sign");
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PayPalUtil.getInstance().stopPayPalService(this);
        EventBus.getDefault().unregister(this);
    }

    public static final int REQUEST_BUY = 111;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_BUY) {
//            DialogUtils.DialogOkMsg(mContext,"支付成功",null);
        }
//       PayPalUtil.getInstance().confirmPayResult(mContext, requestCode, resultCode, data, new PayPalUtil.DoResult() {
//           @Override
//           public void confirmSuccess(String id) {
//               //paypay支付成功，获取到支付id，需提交到后台
//           }
//
//           @Override
//           public void confirmNetWorkError() {
//
//               showToast(R.string.order_pay_faied);
//           }
//
//           @Override
//           public void customerCanceled() {
//               showToast(R.string.order_pay_faied);
//           }
//
//           @Override
//           public void confirmFuturePayment() {
//
//           }
//
//           @Override
//           public void invalidPaymentConfiguration() {
//               showToast(R.string.order_pay_faied);
//           }
//       });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (paypalInfoBean != null) {
            //请求接口查询支付结果
            setResult(Activity.RESULT_OK);
            finish();
//            DialogUtils.DialogOKmsgFinish(mContext,getString(R.string.pay_complete));
        }
    }

    @Subscribe
    public void onEventBus(PayEvent payEvent) {
        if (payEvent.code == -2) {
            hideLoading();
            DialogUtils.DialogOkMsg(mContext, mContext.getString(R.string.order_pay_faied), null);
        } else if (payEvent.code == 0) {
            DialogUtils.DialogOKmsgFinish(mContext, mContext.getString(R.string.order_pay_sucess));
        } else {
            hideLoading();
            DialogUtils.DialogOkMsg(mContext, mContext.getString(R.string.order_pay_faied), null);
        }
    }

    public static final class PayEvent {
        int code;

        public PayEvent(int resultcode) {
            this.code = resultcode;
        }
    }
}
